<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>留言系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
        }
        form {
            margin-bottom: 20px;
        }
        input, textarea {
            width: 100%;
            padding: 10px;
            margin: 5px 0;
            box-sizing: border-box;
        }
        button {
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .message {
            margin-bottom: 10px;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>留言系统</h1>
        <form id="messageForm">
            <input type="text" id="nickname" placeholder="请输入昵称" required>
            <textarea id="message" placeholder="请输入留言" required></textarea>
            <button type="submit">提交</button>
        </form>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const messageForm = document.getElementById('messageForm');
            const nicknameInput = document.getElementById('nickname');
            const messageInput = document.getElementById('message');

            // 提交表单时的处理
            messageForm.addEventListener('submit', function (e) {
                e.preventDefault();

                const nickname = nicknameInput.value.trim(); // trim()方法去除两端空格
                const messageText = messageInput.value.trim();

                if (nickname && messageText) {
                    const message = {
                        id:Date.now(),
                        nickname: nickname,
                        message: messageText
                    };

                    // 将留言对象添加localStorage
                    let messages = JSON.parse(localStorage.getItem('messages')) || [];  // 获取本地存储的留言列表，如果没有则创建一个空数组
                    messages.push(message);
                    localStorage.setItem('messages', JSON.stringify(messages));

                    // 重置表单
                    nicknameInput.value = '';
                    messageInput.value = '';

                    alert('留言成功！');
                }else {
                    alert('昵称和留言不能为空！');
                }
            });
        });
    </script>
</body>
</html>